package com.example.newbilityblog.admin.controller;

import com.example.newbilityblog.admin.service.AdminUserService;
import com.example.newbilityblog.admin.service.mapper.AdminBlogMapper;
import com.example.newbilityblog.blog.api.request.CreateBlogRequest;
import com.example.newbilityblog.blog.api.request.UpdateBlogRequest;
import com.example.newbilityblog.blog.api.response.BlogResponse;
import com.example.newbilityblog.blog.service.BlogAppService;
import com.example.newbilityblog.blog.service.BlogRepresentationService;
import com.example.newbilityblog.common.utils.Result;
import com.example.newbilityblog.common.utils.ResultGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("/admin")
public class AdminController {
    private final AdminUserService adminUserService;
    private final BlogRepresentationService blogRepresentationService;
    private final BlogAppService blogAppService;
    private final AdminBlogMapper adminBlogMapper;

    public AdminController(AdminUserService adminUserService, BlogRepresentationService blogRepresentationService,
                           BlogAppService blogAppService, AdminBlogMapper adminBlogMapper) {
        this.adminUserService = adminUserService;
        this.blogRepresentationService = blogRepresentationService;
        this.blogAppService = blogAppService;
        this.adminBlogMapper = adminBlogMapper;
    }

    @GetMapping("/login")
    public String login() {
        return "/admin/login";
    }

    @PostMapping({"/login"})
    public String login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpSession session) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            session.setAttribute("errorMsg", "用户名或密码不能为空");
            return "/admin/login";
        }

        var adminUser = adminUserService.findByUsernameAndPassword(username, password);

        if (Objects.isNull(adminUser)) {
            session.setAttribute("errorMsg", "登陆失败");
            return "/admin/login";
        } else {
            session.setAttribute("loginUser", adminUser.getUsername());
            session.setAttribute("loginUserId", adminUser.getId());
            return "redirect:/admin/index";
        }
    }

    @GetMapping({"/", "/index", "/index.html"})
    public String index(HttpServletRequest request) {
        request.setAttribute("blogCount", blogRepresentationService.count());
        return "/admin/index";
    }

    @GetMapping("/blogs")
    public String list(HttpServletRequest request) {

        return "/admin/blogs";
    }

    @GetMapping("/blogs/list")
    @ResponseBody
    public List<BlogResponse> listBlogs(@RequestParam Map<String, String> params) {
        if (StringUtils.isBlank(params.get("page")) || StringUtils.isBlank(params.get("limit"))) {
            return null;
        }

        var page = Integer.parseInt(params.get("page")) - 1;
        var limit = Integer.parseInt(params.get("limit"));
        var pageable = PageRequest.of(page, limit);
        return blogRepresentationService.getBlogs(pageable).toList();
    }

    @GetMapping("/blogs/{id}")
    public String blogDetails(HttpServletRequest request, @PathVariable("id") Long id) {
        var blog = blogRepresentationService.getBlog(id);
        request.setAttribute("blog", blog);

        return "/admin/blog";
    }

    @PutMapping("/blogs/{id}")
    @ResponseBody
    public Result update(@PathVariable(value = "id") Long id, @RequestBody UpdateBlogRequest updateBlogRequest) {
        blogAppService.update(id, adminBlogMapper.toUpdateBlogCommand(updateBlogRequest));
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/blogs/edit")
    public String edit(HttpServletRequest request) {
        return "admin/blog";
    }

    @ResponseBody
    @PostMapping("/blogs/save")
    public Result save(@RequestBody CreateBlogRequest request) {
        blogAppService.create(adminBlogMapper.toCreateBlogCommand(request));
        return ResultGenerator.genSuccessResult();
    }

    @ResponseBody
    @DeleteMapping("/blogs")
    public Result delete(@RequestBody List<Long> ids) {
        blogAppService.delete(ids);
        return ResultGenerator.genSuccessResult();
    }
}
